package com.xuhuan.practice.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.xuhuan.practice.properties.JWTProperties;
import java.util.Date;
import java.util.Map;

/**
 * @author: huan.xu
 * @create: 2024/6/10 19:39
 * @description: JWT工具类
 **/
public class JwtUtil {

  private JwtUtil() {
  }

  private static JWTProperties jwtProperties;

  static {
    JwtUtil.jwtProperties = SpringContextUtil.getBean(JWTProperties.class);
  }

  /**
   * 生成JWT令牌
   *
   * @param claims
   * @return
   */
  public static String genToken(Map<String, Object> claims) {
    return JWT.create()
        .withClaim("claims", claims)
        .withExpiresAt(
            new Date(System.currentTimeMillis() + 1000 * 60 * 60 * jwtProperties.getExpiresHour()))
        .sign(Algorithm.HMAC256(jwtProperties.getSecret()));
  }

  /**
   * 解析JWT令牌，并返回业务数据
   *
   * @param token
   * @return
   */
  public static Map<String, Object> parseToken(String token) {
    return JWT.require(Algorithm.HMAC256(jwtProperties.getSecret()))
        .build()
        .verify(token)
        .getClaim("claims")
        .asMap();
  }
}
